<template>
  <div class="manufacturer-container">
    <!-- 标签页 -->
    <div class="boxWrapper tabbox">
      <el-tabs v-model="currentName">
        <el-tab-pane name="1">
          <span slot="label" class="tab-label">
            <i class="iconfont tab-icon">&#xe687;</i> 
            <span>厂家管理</span>
          </span>
        </el-tab-pane>
        <el-tab-pane name="2">
          <span slot="label" class="tab-label">
            <i class="iconfont tab-icon">&#xe6f4;</i> 
            <span>仪器管理</span>
          </span>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 厂家管理内容 -->
    <div class="content-card boxWrapper" v-show="currentName == '1'">
      <!-- 搜索和筛选区域 -->
      <div class="filter-section">
        <div class="search-box">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索厂家名称、城市或电话..."
            prefix-icon="el-icon-search"
            clearable
            @clear="handleSearch"
            @keyup.enter.native="handleSearch"
            size="medium"
          >
            <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
          </el-input>
        </div>
        <div>
            <el-button type="primary"  size="small" @click="manufacturersAdd()" icon="el-icon-plus" v-if="permissions.showRoleAdd">新增厂家</el-button>
        </div>
        
      </div>

      <!-- 表格区域 -->
      <div class="table-section">
        <el-table 
          :data="filteredTableList" 
          v-loading="loading"
          element-loading-text="数据加载中..."
          element-loading-spinner="el-icon-loading"
          height="calc(100vh - 270px)"
        >
          <el-table-column 
            align="center" 
            label="厂家名称" 
            prop="factoryName"
          >
            <template slot-scope="scope">
              <div class="factory-name">
                <i class="el-icon-office-building"></i>
                <span>{{ scope.row.factoryName }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column 
            align="center" 
            label="公司地址" 
            prop="adress" 
            show-overflow-tooltip
          />
          <el-table-column 
            align="center" 
            label="所在城市" 
            prop="city" 
          >
            <template slot-scope="scope">
              <el-tag v-if="scope.row.city" type="info" size="small">
                <i class="el-icon-location"></i>
                {{ scope.row.city }}
              </el-tag>
              <span v-else class="empty-text">-</span>
            </template>
          </el-table-column>
          <el-table-column 
            align="center" 
            label="电话" 
            prop="tel" 
          >
            <template slot-scope="scope">
              <div v-if="scope.row.tel" class="contact-info">
                <i class="el-icon-phone"></i>
                <span>{{ scope.row.tel }}</span>
              </div>
              <span v-else class="empty-text">-</span>
            </template>
          </el-table-column>
          <el-table-column 
            label="操作" 
            align="center" 
          >
            <template slot-scope="scope">
                <el-link 
                  type="primary" 
                  size="mini" 
                  @click="manufacturersAdd(scope.row)" 
                  icon="el-icon-edit"
                  :underline="false"
                   v-if="permissions.showRoleEdit"
                >编辑</el-link>

                <el-link 
                  type="danger" 
                  size="mini" 
                  @click="manufacturersDel(scope.row)" 
                  icon="el-icon-delete"
                  style="margin-left: 18px"
                  :underline="false"
                   v-if="permissions.showRoleDel"
                >删除</el-link>

            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 仪器管理组件 -->
    <instrument v-if="currentName == '2'" :options="tableList" :showRoleAdd="permissions.showRoleAdd" :showRoleEdit="permissions.showRoleEdit" :showRoleDel="permissions.showRoleDel"/>
    <!-- 厂家信息对话框 -->
    <el-dialog 
      title="厂家信息配置" 
      :visible.sync="manufacturersDialog" 
      width="500px" 
      :before-close="handleCloseManufacturersDialog" 
      v-dialogDrag
    >
      <el-form 
        ref="manufacturersFormRef" 
        :model="manufacturersForm" 
        :rules="manufacturersRules"
        label-width="100px"
        class="manufacturer-form"
      >
        <el-form-item label="厂家名称" prop="factoryName">
          <el-input 
            v-model="manufacturersForm.factoryName" 
            placeholder="请输入厂家名称"
            prefix-icon="el-icon-office-building"
            maxlength="50"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="公司地址">
          <el-input 
            v-model="manufacturersForm.adress" 
            placeholder="请输入公司详细地址" 
            type="textarea" 
            :rows="3"
            maxlength="200"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="所在城市">
          <el-input 
            v-model="manufacturersForm.city" 
            placeholder="请输入所在城市"
            prefix-icon="el-icon-location"
            maxlength="20"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input 
            v-model="manufacturersForm.tel" 
            placeholder="请输入联系电话"
            prefix-icon="el-icon-phone"
          ></el-input>
        </el-form-item>
      </el-form>
      <div  class="dialog-footer">
        <el-button @click="handleCloseManufacturersDialog" icon="el-icon-close" class="cancel-btn" size="small">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleSaveManufacturersDialog" 
          icon="el-icon-check"
          :loading="saveLoading"
          class="confirm-btn"
          size="small"
        >
          保存配置
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {GetAllFactory,AddInstrumentFactory,EditInstrumentFactory,DelInstrumentFactory} from '@/api/https'
import instrument from '@/components/page/setting/instrument.vue'
import bus from '@/utils/eventBus.js';
import permissionMixin from '@/utils/permission.js'
export default ({
  name:'manufacturer',
  components:{instrument},
  mixins: [permissionMixin],
  data() {
    return {
      currentName:'1',
      tableList:[],
      filteredTableList: [],
      searchKeyword: '',
      loading: false,
      saveLoading: false,
      editFacture:false,
      manufacturersForm:{
        factoryName: '',
        adress: '',
        city: '',
        tel: ''
      },
      manufacturersDialog:false,
      manufacturersRules: {
        factoryName: [
          { required: true, message: '请输入厂家名称', trigger: 'blur' },
          { min: 2, max: 50, message: '厂家名称长度在 2 到 50 个字符', trigger: 'blur' }
        ],
      }
    } 
  },
  mounted(){
    bus.$emit('showBasin', false);
    this.getFactory();
  },
  activated(){
    bus.$emit('showBasin', false);
  },
  computed: {
    permissions() {
        return this.getPermissions() || {}
    }
  },
  methods:{
    // 获取厂家数据
    getFactory() {
      this.loading = true;
      GetAllFactory().then(res=>{
        if (res.isSuccess) {
          this.tableList = res.data || [];
          this.filteredTableList = [...this.tableList];
        } else {
          this.$message.error(res.errorMessage);
        }
      }).catch(error => {
       
      }).finally(() => {
        this.loading = false;
      });
    },
    
    // 搜索处理
    handleSearch() {
      if (!this.searchKeyword) {
        this.filteredTableList = [...this.tableList];
        return;
      }
      
      const keyword = this.searchKeyword.toLowerCase();
      this.filteredTableList = this.tableList.filter(item => 
        (item.factoryName && item.factoryName.toLowerCase().includes(keyword)) ||
        (item.city && item.city.toLowerCase().includes(keyword)) ||
        (item.tel && item.tel.includes(keyword))
      );
    },
    
    
    // 新增/编辑厂家
    manufacturersAdd(data) {
      if(data){
        this.editFacture = true;
        this.manufacturersForm = {...data};
      } else {
        this.editFacture = false;
        this.manufacturersForm = {
          factoryName: '',
          adress: '',
          city: '',
          tel: ''
        };
      }
      this.manufacturersDialog = true;
      
      // 清除表单验证
      this.$nextTick(() => {
        if (this.$refs.manufacturersFormRef) {
          this.$refs.manufacturersFormRef.clearValidate();
        }
      });
    },
    
    // 删除厂家
    manufacturersDel(data){
      this.$confirm(
        `确定要删除厂家 "${data.factoryName}" 吗？此操作不可恢复。`, 
        '删除确认', 
        {
          type: 'warning',
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          confirmButtonClass: 'el-button--danger',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              instance.confirmButtonLoading = true;
              DelInstrumentFactory({id:data.id}).then(res=>{
                if (res.isSuccess) {
                  this.getFactory();
                  done();
                } else {
                  this.$message.error(res.errorMessage);
                  instance.confirmButtonLoading = false;
                }
              }).catch(error => {
                instance.confirmButtonLoading = false;
              });
            } else {
              done();
            }
          }
        }
      ).then(() => {
        // 确认删除后的回调
      }).catch(() => {
        // 取消删除
      });
    },
    
    // 关闭对话框
    handleCloseManufacturersDialog(){
      this.manufacturersForm = {
        factoryName: '',
        adress: '',
        city: '',
        tel: ''
      };
      this.manufacturersDialog = false;
      this.editFacture = false;
      this.saveLoading = false;
    },
    
    // 保存厂家信息
    handleSaveManufacturersDialog(){
      this.$refs.manufacturersFormRef.validate((valid) => {
        if (valid) {
          this.saveLoading = true;
          
          const savePromise = this.editFacture ? 
            EditInstrumentFactory(this.manufacturersForm) : 
            AddInstrumentFactory(this.manufacturersForm);
            
          savePromise.then(res=>{
            if (res.isSuccess) {
              this.getFactory();
              this.handleCloseManufacturersDialog();
            
            } else {
              this.$message.error(res.errorMessage);
            }
          }).catch(error => {
          }).finally(() => {
            this.saveLoading = false;
          });
        } else {
          this.$message.warning('请完善表单信息');
          return false;
        }
      });
    }
  }
})
</script>

<style scoped lang="scss">
.content-card {
  padding: 16px;
  margin-top:10px;
}

.filter-section {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
  
  .search-box {
    width: 300px;
  }
}

</style>